import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../utils/http_helper.dart';
import '../screens/home/model/comic_category_item_model.dart';

// 书架状态类
class BookshelfState {
  final List<ComicItemModel> items;
  final bool isLoading;
  final bool isLoadingMore;
  final bool hasError;
  final String? errorMessage;
  final bool hasMore;
  final int currentPage;

  const BookshelfState({
    this.items = const [],
    this.isLoading = false,
    this.isLoadingMore = false,
    this.hasError = false,
    this.errorMessage,
    this.hasMore = true,
    this.currentPage = 1,
  });

  BookshelfState copyWith({
    List<ComicItemModel>? items,
    bool? isLoading,
    bool? isLoadingMore,
    bool? hasError,
    String? errorMessage,
    bool? hasMore,
    int? currentPage,
  }) {
    return BookshelfState(
      items: items ?? this.items,
      isLoading: isLoading ?? this.isLoading,
      isLoadingMore: isLoadingMore ?? this.isLoadingMore,
      hasError: hasError ?? this.hasError,
      errorMessage: errorMessage ?? this.errorMessage,
      hasMore: hasMore ?? this.hasMore,
      currentPage: currentPage ?? this.currentPage,
    );
  }
}

// 书架数据管理器
class BookshelfNotifier extends StateNotifier<BookshelfState> {
  final int type; // 0: 浏览记录, 1: 收藏
  static const int pageSize = 20;

  BookshelfNotifier(this.type) : super(const BookshelfState()) {
    loadData(isRefresh: true);
  }

  // 加载数据
  Future<void> loadData({bool isRefresh = false}) async {
    if (isRefresh) {
      state = state.copyWith(
        isLoading: true,
        hasError: false,
        errorMessage: null,
        currentPage: 1,
      );
    } else {
      if (state.isLoadingMore || !state.hasMore) return;
      state = state.copyWith(isLoadingMore: true);
    }

    try {
      print(
          '[书架] 开始请求数据 - Type: $type, PageSize: $pageSize, PageNo: ${isRefresh ? 1 : state.currentPage}');

      final response = await HttpUtil().getModel<List<ComicItemModel>>(
        'Comic/GetComicLogList',
        params: {
          "Type": type,
          "PageSize": pageSize,
          "PageNo": isRefresh ? 1 : state.currentPage,
        },
        fromJson: (json) {
          print('[书架] 解析响应数据，原始数据类型: ${json.runtimeType}');
          if (json is List) {
            print('[书架] 数组长度: ${json.length}');
            return json.map((item) {
              print('[书架] 解析项目: $item');
              // 从收藏记录中提取comic数据
              final comicData = item['comic'];
              if (comicData != null) {
                print('[书架] 找到comic字段，解析漫画数据: ${comicData['title']}');
                return ComicItemModel.fromJson(comicData);
              } else {
                print('[书架] 未找到comic字段，直接解析项目数据');
                // 如果没有comic字段，尝试直接解析（兼容其他接口）
                return ComicItemModel.fromJson(item);
              }
            }).toList();
          } else {
            print('[书架] 错误：响应数据不是数组类型');
            return <ComicItemModel>[];
          }
        },
      );
      print(
          '[书架] 请求响应 - status: ${response?.status}, result为空: ${response?.result == null}');

      if (response?.status == 200 && response?.result != null) {
        final newItems = response!.result!;
        print('[书架] 成功解析 ${newItems.length} 个漫画项目');
        print(
            '[书架] 第一个项目标题: ${newItems.isNotEmpty ? newItems.first.title : "无数据"}');
        final hasMore = newItems.length >= pageSize;

        if (isRefresh) {
          state = state.copyWith(
            items: newItems,
            isLoading: false,
            hasError: false,
            hasMore: hasMore,
            currentPage: 2,
          );
        } else {
          state = state.copyWith(
            items: [...state.items, ...newItems],
            isLoadingMore: false,
            hasMore: hasMore,
            currentPage: state.currentPage + 1,
          );
        }
      } else {
        print(
            '[书架] 请求失败 - status: ${response?.status}, message: ${response?.message}');
        state = state.copyWith(
          isLoading: false,
          isLoadingMore: false,
          hasError: true,
          errorMessage: response?.message ?? 'Failed to load data',
        );
      }
    } catch (e) {
      print('[书架] 请求异常: $e');
      state = state.copyWith(
        isLoading: false,
        isLoadingMore: false,
        hasError: true,
        errorMessage: e.toString(),
      );
    }
  }

  // 刷新数据
  Future<void> refresh() async {
    await loadData(isRefresh: true);
  }

  // 加载更多
  Future<void> loadMore() async {
    await loadData(isRefresh: false);
  }

  // 重试
  Future<void> retry() async {
    await loadData(isRefresh: true);
  }
}

// Provider 定义
final favoritesProvider =
    StateNotifierProvider<BookshelfNotifier, BookshelfState>(
  (ref) => BookshelfNotifier(1), // Type 1: 收藏
);

final historyProvider =
    StateNotifierProvider<BookshelfNotifier, BookshelfState>(
  (ref) => BookshelfNotifier(0), // Type 0: 浏览记录
);

// 书架Tab状态
final bookshelfTabProvider = StateProvider<int>((ref) => 0);
final isSelectionModeProvider = StateProvider<bool>((ref) => false);
final selectedComicsProvider = StateProvider<Set<String>>((ref) => {});
